﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;

namespace Lg.Core.Extensions
{
   public static class JsonHelperExtensions
    {
        /// <summary>
        /// Json文件解析，默认读取appsttings.json的内容，通过结点名称(属性访问规则的字符串)来获取指定结点的数据
        /// </summary>
        /// <param name="jsonHelper">扩展对像(接口类型)</param>
        /// <param name="nodes">结点名称(属性访问规则的字符串)例"name.attr.attr"</param>
        /// <returns></returns>
        public static string GetValue(this IJsonHelper jsonHelper,string nodes)
        {
            string[] _nodeArr=nodes.Split('.');
            IConfigurationSection _section = jsonHelper.root.GetSection(_nodeArr[0]);
            string[] _arr= _nodeArr.Skip(1).ToArray();
            foreach(var node in _arr)
            {
                _section= _section.GetSection(node);
            }
            return _section.Value;
        }
        /// <summary>
        /// Json文件解析，传入指定json文件路径进行解析，通过结点名称(属性访问规则的字符串)来获取指定结点的数据
        /// </summary>
        /// <param name="jsonHelper">扩展对像(接口类型)</param>
        /// <param name="path">指定json文件路径</param>
        /// <param name="nodes">结点名称(属性访问规则的字符串)例"name.attr.attr"</param>
        /// <returns></returns>
        public static string GetValue(this IJsonHelper jsonHelper, string path, string nodes)
        {
            IConfigurationBuilder _builder = new ConfigurationBuilder().AddJsonFile(path);
            IConfigurationRoot _root = _builder.Build();
            string[] _nodeArr = nodes.Split('.');
            IConfigurationSection _section = _root.GetSection(_nodeArr[0]);
            string[] _arr = _nodeArr.Skip(1).ToArray();
            foreach (var node in _arr)
            {
                _section = _section.GetSection(node);
            }
            return _section.Value;
        }
    }
}
